package com.cyf.plc.ui.fragment.set

import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.widget.EditText
import android.widget.TextView
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreference
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.callbacks.onPreShow
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.cyf.plc.BuildConfig
import com.cyf.plc.R
import com.cyf.plc.bean.PlcWriteAttribute
import com.cyf.plc.bean.SettingStatus
import com.cyf.plc.bean.SystemStatus
import com.cyf.plc.constant.Constants
import com.cyf.plc.plc.PlcExecutor
import com.cyf.plc.util.showToast
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.text.SimpleDateFormat
import java.util.*

class SettingFragment : PreferenceFragmentCompat(),Preference.OnPreferenceChangeListener{

    var settingStatus: SettingStatus = SettingStatus(0f)

    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        addPreferencesFromResource(R.xml.root_preferences)
        //设置plc 地址
        findPreference<Preference>("plcIp")?.setOnPreferenceClickListener {
            context?.let { it1 ->
                MaterialDialog(it1).show {
                    onPreShow { dialog ->
                        val etPlcIp: EditText = dialog.getCustomView().findViewById(R.id.et_plc_ip)
                        etPlcIp.setText(PlcExecutor.getPlcIp())
                    }
                    customView(R.layout.dialog_plc_ip)
                    positiveButton(R.string.sure) { dialog ->
                        val etPlcIp: EditText = dialog.getCustomView().findViewById(R.id.et_plc_ip)
                        PlcExecutor.savePlcIp(etPlcIp.text.toString())
                    }
                    negativeButton(R.string.cancel)
                    lifecycleOwner(this@SettingFragment)
                }
            }
            false
        }

        findPreference<SwitchPreference>("workDayClock")?.setOnPreferenceChangeListener(this)
        findPreference<SwitchPreference>("holidayClock")?.setOnPreferenceChangeListener(this)
        findPreference<Preference>("timeSetInWork")?.setOnPreferenceClickListener{
            showSetTimeDialog(Constants.SETTING_WORK_CLOCK_START,Constants.SETTING_WORK_CLOCK_END,settingStatus.workDayClockTime)
        }
        findPreference<Preference>("timeSetInHoliday")?.setOnPreferenceClickListener{
            showSetTimeDialog(Constants.SETTING_HOLIDAY_CLOCK_START,Constants.SETTING_HOLIDAY_CLOCK_END,settingStatus.holidayClockTime)
        }
        //版本号
        findPreference<Preference>("about")?.setSummary("版本号:" + BuildConfig.VERSION_NAME)

    }

    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    fun updateSystem(settingStatus: SettingStatus){
        this.settingStatus = settingStatus
        findPreference<SwitchPreference>("workDayClock")?.isChecked = settingStatus.workDaySwitch
        findPreference<SwitchPreference>("holidayClock")?.isChecked = settingStatus.holidaySwitch
        findPreference<Preference>("energy")?.setSummary("当前能耗:"+ settingStatus.settingEnergy)
    }

    private fun showSetTimeDialog(startPoint:Int,endPoint:Int,clockTime:String): Boolean {
        context?.let {
            MaterialDialog(it).show {
                onPreShow { dialog ->
                    val tvTitle: TextView = dialog.getCustomView().findViewById(R.id.tvTitle)
                    tvTitle.setText("设置定时时间")
                    val etPlcIp: EditText = dialog.getCustomView().findViewById(R.id.et_plc_ip)
                    etPlcIp.setText(clockTime)
                }
                customView(R.layout.dialog_plc_ip)
                positiveButton(R.string.sure) { dialog ->
                    val etPlcIp: EditText = dialog.getCustomView().findViewById(R.id.et_plc_ip)
                    var clockTime = etPlcIp.text.toString()
                    if (TextUtils.isEmpty(clockTime) || !clockTime.contains("-")) {
                        showToast("非法参数！")
                        return@positiveButton
                    }
                    var split = clockTime.split("-")
                    var plcWriteStart = PlcWriteAttribute(
                        startPoint,
                        split[0].toFloat(),
                        Constants.VD
                    )
                    PlcExecutor.write(plcWriteStart)
                    var plcWriteEnd = PlcWriteAttribute(
                        endPoint,
                        split[1].toFloat(),
                        Constants.VD
                    )
                    Log.d(
                        "SettingFragment",
                        plcWriteStart.toString() + "---" + plcWriteEnd.toString()
                    )
                    PlcExecutor.write(plcWriteEnd)
                }
                negativeButton(R.string.cancel)
                lifecycleOwner(this@SettingFragment)
            }
        }
        return true
    }

    override fun onPreferenceChange(preference: Preference?, newValue: Any?): Boolean {
        preference?.let {
            //newValue 开-true 关false
            if (it.key.equals("workDayClock")){
                var value = if (newValue as Boolean && newValue) Constants.POWER_ON else Constants.POWER_OFF
                var plcWriteEnd = PlcWriteAttribute(
                    Constants.SETTING_WORK_TIME_SWITCH,
                    value,
                    Constants.VW
                )
                Log.d("SettingFragment",plcWriteEnd.toString())
                PlcExecutor.write(plcWriteEnd)
            }
            if (it.key.equals("holidayClock")){
                var value = if (newValue as Boolean && newValue) Constants.POWER_ON else Constants.POWER_OFF
                var plcWriteEnd = PlcWriteAttribute(
                    Constants.SETTING_HOLIDAY_TIME_SWITCH,
                    value,
                    Constants.VW
                )
                Log.d("SettingFragment",plcWriteEnd.toString())
                PlcExecutor.write(plcWriteEnd)
            }
        }
        Log.d("SettingFragment", preference?.key + newValue.toString())
        return true
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}
